package com.cloud.service.impl;

import com.cloud.entity.Goods;
import com.cloud.entity.Order;
import com.cloud.entity.PageInfo;
import com.cloud.mapper.GoodsMapper;
import com.cloud.mapper.OrderMapper;
import com.cloud.service.OrderService;
import com.cloud.utils.GlobalConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;



@Service
public class OrderServiceImpl implements OrderService {

    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    private OrderMapper orderMapper;
    private GoodsMapper goodsMapper;

    public OrderServiceImpl(OrderMapper orderMapper, GoodsMapper goodsMapper) {
        this.orderMapper = orderMapper;
        this.goodsMapper = goodsMapper;
    }

    @Override
    public int addOrder(Order order) {
        order.setNo(UUID.randomUUID().toString().replace("-", ""));
        Goods goods = goodsMapper.findGoodsByName(order.getGoods());
        order.setMulti(goods.getPrice() * order.getCount());
        Date date = new Date();
        order.setCtime(date);
        order.setUtime(date);
        order.setStatus(1);
        int result = orderMapper.addOrder(order);
        goods.setWarehouse(goods.getWarehouse() - order.getCount());
        int subGoodsWarehouse = goodsMapper.updateGoods(goods);
        if (result > 0) {
            logger.info("订单【{}】提交成功!", order.getNo());
            return result == subGoodsWarehouse ? GlobalConstant.SUCCESS : GlobalConstant.ERROR;
        }
        logger.info("订单【{}】提交失败!", order.getNo());
        return GlobalConstant.ERROR;
    }

    @Override
    public int delOrder(int id) {
        int result = orderMapper.delOrder(id);
        if (result > 0) {
            logger.info("订单信息删除成功!");
            return GlobalConstant.SUCCESS;
        }
        logger.info("订单信息删除失败!");
        return GlobalConstant.ERROR;
    }

    @Override
    public int updateOrder(Order order) {
        Goods goods = goodsMapper.findGoodsByName(order.getGoods());
        order.setMulti(goods.getPrice() * order.getCount());
        order.setUtime(new Date());
        int result = orderMapper.updateOrder(order);
        if (result > 0) {
            logger.info("订单信息更新成功!");
            return GlobalConstant.SUCCESS;
        }
        logger.info("订单信息更新失败!");
        return GlobalConstant.ERROR;
    }

    @Override
    public PageInfo<Order> findAllOrdersByPage(PageInfo<Order> info, String no) {
        if (StringUtils.isEmpty(no)) no = null;
        info.setCount(orderMapper.getOrdersCount(no));
        info.setData(orderMapper.findAllOrdersByPage((info.getPage() - 1) * info.getLimit(), info.getLimit(), no));
        return info;
    }

    @Override
    public Order findById(int id) {
        return orderMapper.findById(id);
    }
}
